#include <iostream>
#include <string>
#include <websocketpp/server.hpp>
#include <websocketpp/config/asio_no_tls.hpp>

using namespace std;
using websocketpp::lib::placeholders::_1;
using websocketpp::lib::placeholders::_2;
using websocketpp::lib::bind;

typedef websocketpp::server<websocketpp::config::asio> wsserver_t;

void open_callback(wsserver_t* svr, websocketpp::connection_hdl hdl)
{
    cout<< "websocket握手成功！！！" <<endl;
}
void close_callback(wsserver_t* svr, websocketpp::connection_hdl hdl)
{
    cout<< "websocket链接断开！！！" <<endl;

}
void http_callback(wsserver_t* svr, websocketpp::connection_hdl hdl)
{
    // 给客户端返回一个“hello world” 页面
    wsserver_t::connection_ptr conn = svr->get_con_from_hdl(hdl);
    cout <<"body: " << conn->get_request_body() << endl;
    websocketpp::http::parser::request req = conn->get_request();
    cout << "method: " << req.get_method() << endl;
    cout << "uri: " << req.get_uri() << endl;

    string body = "<html><body><h1>Hello World</h1></body></html>";
    conn->set_body(body);
    conn->append_header("Content-Type","text/html");
    conn->set_status(websocketpp::http::status_code::ok);

}
void message_callback(wsserver_t* svr, websocketpp::connection_hdl hdl,wsserver_t::message_ptr msg)
{
    wsserver_t::connection_ptr conn = svr->get_con_from_hdl(hdl);
    cout << "WSmsg: " << msg->get_payload() << endl;
    string rsp = "client say:" + msg->get_payload();
    conn->send(rsp);    // 第二个参数默认为websocketpp::frame::opcode::text
}
int main()
{
    // 1. 实例化server对象
    wsserver_t wssvr;
    // 2. 设置日志等级
    wssvr.set_access_channels(websocketpp::log::alevel::none);
    // 3. 初始化asio调度器
    wssvr.init_asio(); 
    wssvr.set_reuse_addr(true);
    // 4. 设置回调函数
    wssvr.set_open_handler(bind(&open_callback, &wssvr, _1));
    wssvr.set_close_handler(bind(&close_callback, &wssvr, _1));
    wssvr.set_http_handler(bind(&http_callback, &wssvr, _1));
    wssvr.set_message_handler(bind(&message_callback, &wssvr, _1, _2));

    // 5. 设置监听端口
    wssvr.listen(8080);
    // 6. 开始获取新链接
    wssvr.start_accept();
    // 7. 启动服务器
    wssvr.run();




    return 0;
}